local p = {}
local getArgs = require('Module:Arguments').getArgs
local inArray = require('Module:Util').inArray
local OrderedTable = require('Module:OrderedTable')

local ELEMENT_MAP = require('Module:Util/Config').ELEMENT_MAP
local RARITY_MAP = require('Module:Util/Config').RARITY_MAP
local TYPE_NAME_MAP = require('Module:Util/Config').TYPE_NAME_MAP 
local WEAPON_MAP = require('Module:Util/Config').WEAPON_MAP 
local split_swap = require('Module:Util/SwapImages').split_swap
local character_map = require('Module:Util/Character')
local story_map = require('Module:Util/CharacterStory')
local item_map = require('Module:Util/Item')

-----------------------------------------------------------------------------
-- 读取角色信息
-----------------------------------------------------------------------------

function p.query_data(character_id)
	local card_info = character_map[''..character_id or ''] or ''
	card_info.id = character_id
	return card_info
end

function p.query_story_data(character_id)
	local card_info = story_map[''..character_id or ''] or ''
	card_info.id = character_id
	return card_info
end

-----------------------------------------------------------------------------
-- 生成故事组件
-----------------------------------------------------------------------------
function p.story(card_info)
	local html = mw.html.create():tag('div'):addClass('role-skill-story'):attr('data-id', 1)
	html:tag('p'):tag('br')
	html:tag('h2'):wikitext('盈缺笔记')
	local table = html:tag('table'):addClass('border-color')
	local cnData = card_info.cnData or ''
	local titleList = {"角色资料·一","角色资料·二","角色资料·三","角色资料·四","盈缺评价"}

	for i, str in ipairs(cnData) do
		table:tag('tr'):tag('th'):addClass('background-color'):wikitext(titleList[i])
		table:tag('tr'):tag('td'):addClass('background-color-2'):wikitext(str)
	end
	
	html:tag('h2'):wikitext('语音')
	local table = html:tag('table'):addClass('border-color')

	if (card_info.gcv or '') ~= '' then
		table:tag('tr'):tag('th'):addClass('background-color'):wikitext(string.sub(card_info.gcv['name'],8)):tag('td'):addClass('background-color-2'):wikitext(card_info.gcv['des'])
	end
	local cv = card_info.cv or ''
	for i, data in ipairs(cv) do
		table:tag('tr'):tag('th'):addClass('background-color'):wikitext(string.sub(data['name'],8)):tag('td'):addClass('background-color-2'):wikitext(data['des'])
	end
	local dcv = card_info.dailyCv or ''
	for i, data in ipairs(dcv) do
		table:tag('tr'):tag('th'):addClass('background-color'):wikitext(string.sub(data['name'],8)):tag('td'):addClass('background-color-2'):wikitext(data['des'])
	end

        local result_str = tostring(html)
	result_str = mw.ustring.gsub(result_str, '_name_', '探求者')
	return result_str 
end

-----------------------------------------------------------------------------
-- 生成角色表格
-----------------------------------------------------------------------------

function p.left(frame)
	local args = getArgs(frame)
	local character_id = tonumber(mw.text.split(args.pagename, '/')[2]) or tonumber(args.pagename)
	if not character_id then
		return '【错误】提供的ID有错误'
	end
	
	local card_info = p.query_data(character_id or '')

	if card_info == '' then
		return '【错误】没有找到ID相同的角色信息，请到角色列表进行更新修正。'
	end

	mw.ext.displaytitle.set(card_info.nickname or card_info.name)
	
	local half_html = '<div class="role-box element-'..(card_info.element or '0')..'"><div class="role-left">'
	
	local html = mw.html.create():tag('div'):addClass('role-base-info')
	
	local title = html:tag('div'):addClass('role-base-title color-box color-frame')
	title:tag('div'):wikitext('['..(card_info.prefix or '')..']'):done()
	title:tag('div'):wikitext((card_info.name or '')):done()
	title:tag('div'):addClass('role-base-icon'):wikitext('[[File:rarity_'..card_info.rarity..'.png]]'):done()
	title:done()
	
	local imgBox = html:tag('div'):addClass('role-base-img-box')
	--立绘
	
	local zoom_img_div = imgBox:tag('div'):addClass('role-base-img-group')
	local filter_div = imgBox:tag('div'):addClass('role-base-img-btn-group')
	
	local zoom_list = {'01', '02'}
	local zoom_name_map = {
		['01'] = '初始',
		['02'] = '突破',
	}
	local zoom_name_map_gender = {
		['01_1'] = '初始2',
		['02_1'] = '突破2',
	}
	local extra_zoom_list = {}
	for _, zoom_id in ipairs(mw.text.split(args['额外立绘'] or '', ',')) do
		zoom_id = tostring(zoom_id)
		if zoom_id ~= '' and not inArray(extra_zoom_list, zoom_id) then
			table.insert(extra_zoom_list, zoom_id)
		end
	end
	for _, zoom_id in ipairs(card_info.extra_img or {}) do
		zoom_id = tostring(zoom_id)
		if zoom_id ~= 'false' and  zoom_id ~= '' and not inArray(extra_zoom_list, zoom_id) then
			table.insert(extra_zoom_list, zoom_id)
		end
	end
	local extra_zoom_count=#extra_zoom_list
	for extra_zoom_index, extra_zoom_id in ipairs(extra_zoom_list) do
		if zoom_name_map_gender[extra_zoom_id] then
			extra_zoom_count=extra_zoom_count-1
			table.insert(zoom_list, extra_zoom_id)
		end
	end
	table.sort(zoom_list)
	
	for extra_zoom_index, extra_zoom_id in ipairs(extra_zoom_list) do
		if not zoom_name_map_gender[extra_zoom_id] then
			if extra_zoom_count == 1 then
				zoom_name_map[extra_zoom_id] = '额外'
			else
				zoom_name_map[extra_zoom_id] = '额外'..extra_zoom_index
			end
			table.insert(zoom_list, extra_zoom_id)
		end
	end
	
	local dataid = 0
	for _, zoom_id in ipairs(zoom_list) do
		local zoom_div = zoom_img_div:tag('div'):addClass('role-base-img'):attr('data-id', dataid)
		local filter_btn = filter_div:tag('div'):addClass('role-base-img-btn border-color'):attr('data-id', dataid):wikitext(zoom_name_map[zoom_id])
 
		if zoom_id == '01' then
			filter_btn:addClass('active')
		end
		local zoom_id_text = tostring(zoom_id)
		if #zoom_id_text == 1 then
			zoom_id_text = '0'..zoom_id_text
		end
 
		zoom_div:wikitext('[[File:'..(card_info.id or '')..'_'..zoom_id_text..'.png|600px]]')
		dataid = dataid + 1
	end

	local half_html_end = '<div class="role-skill-story-box"><div class="role-skill-story-btn-group"><div class="role-skill-story-btn border-color active" data-id="0">技能</div><div class="role-skill-story-btn border-color" data-id="1">图鉴</div></div><div class="role-skill-story data-id="0">'
	
	return half_html..tostring(html)..half_html_end
end

function t_sort(a,b)
	return a[1] < b[1]
end

function p.print_table(html, data)
	local tmp_table = {}
	for itemid, detail in pairs(data) do
		table.insert(tmp_table, {itemid,detail})
	end
	table.sort(tmp_table, t_sort)

	for _, v in ipairs(tmp_table) do
		local itemid = v[1]
		local detail = v[2]
		local tb = html:tag('tr')
		local itemDetail = item_map[itemid..'' or ''] or ''
		local icon = itemid
		if (itemDetail.icon or '') ~= '' then
			icon = itemDetail.icon
		end
		local name = itemDetail.name or ''
		if (itemDetail.nickname or '') ~= '' then
			name = itemDetail.nickname
		end
		local itemTxt = '[[File:Item_'..icon..'.png|25px|link=Item/'..(itemid or '')..']]'..(name or '')
		tb:tag('td'):wikitext(itemTxt)
		if (detail or '' ~= '') then
			local i = 0
			for i=1,#detail do
				tb:tag('td'):wikitext(detail[i])
			end
		end
	end
end


function p.right(frame)
local args = getArgs(frame)
	local character_id = tonumber(mw.text.split(args.pagename, '/')[2]) or tonumber(args.pagename)
	if not character_id then
		return '【错误】提供的ID有错误'
	end

	local story_info = p.query_story_data(character_id or '')

	if story_info == '' then
		return '【错误】没有找到ID相同的角色信息，请到角色列表进行更新修正。'
	end

	local story_html = p.story(story_info)

	local card_info = p.query_data(character_id or '')

	if card_info == '' then
		return '【错误】没有找到ID相同的角色信息，请到角色列表进行更新修正。'
	end
	
	local half_html = '</div><div class="role-right"><div class="role-info color-box color-frame">'
	
	local html = mw.html.create()
	html:tag('div'):addClass('role-right-title'):wikitext('基本信息'):done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('血量'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.minHp or '')..' ➔ '..(card_info.maxHp or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('攻击力'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.minAtk or '')..' ➔ '..(card_info.maxAtk or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('属性'):done():tag('div'):addClass('role-right-box-content'):wikitext('[[File:Element_'..(card_info.element or '')..'.png|25px]]'..(ELEMENT_MAP[(card_info.element or '')] or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('种族'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.race or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('类型'):done():tag('div'):addClass('role-right-box-content'):wikitext('[[File:CharType_'..(card_info.type or '')..'.png|25px]] '..(TYPE_NAME_MAP[(card_info.type or '')] or '')):done():done()
	local weapon = '[[File:CharWeapon_'..(card_info.weapon1 or '')..'.png|25px]] '..(WEAPON_MAP[(card_info.weapon1 or '')] or '')
	if (card_info.weapon2 or '') ~= '' then
		weapon = weapon .. '[[File:CharWeapon_'..(card_info.weapon2 or '')..'.png|25px]] '..(WEAPON_MAP[(card_info.weapon2 or '')] or '')
	end
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('得意武器'):done():tag('div'):addClass('role-right-box-content'):wikitext(weapon):done():done()
	if (card_info.zx_img or '') ~= '' then
		html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('满同调额外血量'):done():tag('div'):addClass('role-right-box-content'):wikitext(card_info.td_hp or ''):done():done()
		html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('满同调额外攻击力'):done():tag('div'):addClass('role-right-box-content'):wikitext(card_info.td_atk or ''):done():done()
		html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('阵型'):done():tag('div'):addClass('role-right-box-content'):wikitext('[[File:'..(card_info.zx_img or '')..'.png|80px]]'):done():done()
		
		local zxmsg
		if (card_info.zx or '') ~= '' then --新版本
			zxmsg = '[[File:Status_'..(card_info.zx.b1.icon or '')..'.png]]'..(card_info.zx.b1.name or '')..'+'..(card_info.zx.b1.value or '')..'%<br>'
			zxmsg = zxmsg..'[[File:Status_'..(card_info.zx.b2.icon or '')..'.png]]'..(card_info.zx.b2.name or '')..'+'..(card_info.zx.b2.value or '')..'%<br>'
			zxmsg = zxmsg..'[[File:Status_'..(card_info.zx.p.icon or '')..'.png]]'..(card_info.zx.p.name or '')..'+'..(card_info.zx.p.value or '')..'%(紫)<br>'
		else
			zxmsg = (card_info.zx_b1 or '')..'+7.3%<br>'..(card_info.zx_b2 or '')..'+4.94%<br>'
			if (card_info.zx_p or '') == '1' then
				zxmsg = zxmsg..'攻击系数+4%(紫)'
			else
				zxmsg = zxmsg..'攻击系数+3%(紫)'
			end
		end
		html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('加成'):done():tag('div'):addClass('role-right-box-content'):wikitext(zxmsg):done():done()
	end
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('加入时间'):done():tag('div'):addClass('role-right-box-content'):wikitext((os.date("%Y年%m月%d日",card_info.addDate) or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('性别'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.gender or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('年龄'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.age or '')):done():done()
	html:tag('div'):addClass('role-right-box-2 color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('生日'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.birth or '')):done():done()
	html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('英文名'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.enName or '')):done():done()
	html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('声优'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.jpVoice or '')):done():done()
	html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('画师'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.designer or '')):done():done()
	html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('喜好'):done():tag('div'):addClass('role-right-box-content'):wikitext((card_info.favourite or '')):done():done()

	local num = {'Ⅰ','Ⅱ','Ⅲ','Ⅳ','Ⅴ'}

	if (card_info.spget or '') ~= '' then --解放素材
		local uncapDiv = html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('解放素材'):done():tag('div'):addClass('role-right-box-content'):tag('table'):attr('border',2)
		local head = uncapDiv:tag('tr')
		head:tag('th'):wikitext('阶段')
		for i = 1,3 do
			head:tag('th'):wikitext(num[i])
		end
		p.print_table(uncapDiv, card_info.spget)
	end

	if (card_info.uncap or '') ~= '' then --突破素材
		local uncapDiv = html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('突破素材'):done():tag('div'):addClass('role-right-box-content'):tag('table'):attr('border',2)
		local head = uncapDiv:tag('tr')
		head:tag('th'):wikitext('阶段')
		for i = 2,4 do
			head:tag('th'):wikitext(num[i])
		end
		p.print_table(uncapDiv, card_info.uncap)
	end

	if (card_info.kochab or '') ~= '' then --同调素材
		local uncapDiv = html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('同调素材'):done():tag('div'):addClass('role-right-box-content'):tag('table'):attr('border',2)
		local head = uncapDiv:tag('tr')
		head:tag('th'):wikitext('阶段')
		for i = 1,5 do
			head:tag('th'):wikitext(num[i])
		end
		p.print_table(uncapDiv, card_info.kochab)
	end

	if (card_info.spuncap or '') ~= '' then --固有素材
		local uncapDiv = html:tag('div'):addClass('role-right-box color-frame-2'):tag('div'):addClass('role-right-box-title'):wikitext('固有能力强化素材'):done():tag('div'):addClass('role-right-box-content'):tag('table'):attr('border',2)
		local head = uncapDiv:tag('tr')
		head:tag('th'):wikitext('阶段')
		for i = 1,4 do
			head:tag('th'):wikitext(num[i])
		end
		p.print_table(uncapDiv, card_info.spuncap)
	end


	return '</div>'..story_html..'</div>'..half_html..tostring(html)..'</div></div></div>'
end

return p
